package swan

import (
	"bytes"
	"encoding/binary"
	"io"
	"os"
)

func Parse(filepath string) (*SwanModel, error) {
	data, err := os.ReadFile(filepath)
	if err != nil {
		return nil, err
	}
	return parseBin(bytes.NewReader(data))
}

// 解析二进制文件reader对象
func parseBin(reader io.Reader) (*SwanModel, error) {
	swanHeader := SwanHeader{}
	err := binary.Read(reader, binary.LittleEndian, &swanHeader) // 1024
	if err != nil {
		return nil, err
	}

	xGridNum := swanHeader.X_grid_num
	yGridNum := swanHeader.Y_grid_num

	dataResult := make([][]*float64, yGridNum)
	for i := range yGridNum {
		dataResult[i] = make([]*float64, xGridNum)
		for j := range xGridNum {
			var v int8
			err = binary.Read(reader, binary.LittleEndian, &v) // 64
			if err != nil {
				continue
			}
			if v <= 0 {
				continue
			}
			s := float64(v-66) / 2
			dataResult[i][j] = &s
		}
	}
	return &SwanModel{
		SwanHeader: swanHeader,
		Data:       dataResult,
	}, nil
}
